package com.pss.common.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.pss.common.response.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Map;
public class CURDController<S extends IService<T>, T> {

    @Autowired
    private S service;

    @PostMapping("/save")
    public Response save(T t) {
        return Response.success(service.saveOrUpdate(t));
    }

    @PostMapping("/delete")
    public Response delete(int id) {
        return Response.success(service.removeById(id));
    }

    @PostMapping("/getById")
    public Response getById(int id) {
        return Response.success(service.getById(id));
    }

    @PostMapping("/list")
    public Response list(@RequestBody CURDRequestEntity curdRequest) {
        QueryWrapper qw = new QueryWrapper<T>();
        List<String> selectColumns = curdRequest.getSelectColumns();
        if (!CollectionUtils.isEmpty(selectColumns)) {
            qw.select(selectColumns);
        }
        Boolean orderBy = curdRequest.getOrderBy() == null ? true : curdRequest.getOrderBy();
        List<String> orderByColumns = curdRequest.getOrderByColumns();
        if (!CollectionUtils.isEmpty(orderByColumns)) {
            if (orderBy) {
                qw.orderByAsc(orderByColumns);
            } else {
                qw.orderByDesc(orderByColumns);
            }
        }
        Map<String, Object> eqMap = curdRequest.getEqMap();
        eqMap.keySet().forEach(column -> {
            qw.eq(column, eqMap.get(column));
        });

        Map<String, Object> likeMap = curdRequest.getLikeMap();
        likeMap.keySet().forEach(column -> {
            qw.like(column, likeMap.get(column));
        });

        Map<String, List> inMap = curdRequest.getInMap();
        inMap.keySet().forEach(column -> {
            qw.in(column, inMap.get(column));
        });

        Object data;
        Integer page = curdRequest.getPage();
        Integer limit = curdRequest.getLimit();
        if (page != null && limit != null) {
            data = service.page(new Page<T>(page, limit), qw);
        } else {
            data = service.list(qw);
        }
        return Response.success(data);
    }

}
